<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace support\utils;

class BcMath
{
    private static int $scale = 2;

    public static function setScale(int $s)
    {
        self::$scale = $s;
    }

    public static function resetScale()
    {
        self::$scale = 2;
    }

    public static function bcAdd(...$arr)
    {
        if (! $arr) {
            return 0;
        }
        if (count($arr) == 1) {
            return floatval($arr[0]);
        }
        $sum = 0;
        foreach ($arr as $item) {
            $sum = bcadd(strval($sum), strval($item), self::$scale);
        }
        return floatval($sum);
    }

    public static function bcSub(...$arr)
    {
        if (! $arr) {
            return 0;
        }
        if (count($arr) == 1) {
            return floatval($arr[0]);
        }
        $sum = $arr[0];
        array_shift($arr);
        foreach ($arr as $item) {
            $sum = bcsub(strval($sum), strval($item), self::$scale);
        }
        return floatval($sum);
    }

    public static function bcAddArr($arr)
    {
        return self::bcAdd(...$arr);
    }

    public static function bcSubArr($arr)
    {
        return self::bcSub(...$arr);
    }

    // 3*11=33.00 乘法
    public static function bcMul($num1, $num2, $scale = 2)
    {
        return bcmul($num1, $num2, 2);
    }

    // 33/3=11 除法
    public static function bcDiv($num1, $num2, $scale = 2)
    {
        return bcdiv($num1, $num2, $scale);
    }
}
